package com.cl.service;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cl.dto.WordDTO;

@Service
public class MSOfficeService {
	 @Autowired
	 private FileService fileService;
	
	 public WordDTO getWordTxt( String fp) throws Exception {
		  InputStream is = new FileInputStream(fileService.getPathUpload()+fp);  
		  HWPFDocument doc  = new HWPFDocument(is);
		  WordExtractor extractor = new WordExtractor(doc);   
	      WordDTO wd = new WordDTO();
	      wd.success=true;
	      wd.txt = extractor.getText();
	      wd.count = doc.getSummaryInformation().getCharCount();
	      //---int count = doc.getSummaryInformation().getWordCount();
	      extractor.close();
	      return wd;
	      
	      //wl
	      /*StringBuffer buffer = new StringBuffer();
	      WordDTO wd1 = new WordDTO();
	        InputStream input = null;
	        WordExtractor extractor1 = null;
	        String[] paragraphs = null;
	        try {
	            input = new FileInputStream(fileService.getPathUpload()+fp);
	            extractor1 = new WordExtractor(input);
	            paragraphs = extractor1.getParagraphText();
	            for (String paragraph : paragraphs) {
	                buffer.append(extractor1.stripFields(paragraph)).append("\\r\\n");
	            }
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            if (input != null) {
	                input.close();
	            }
	        }
		      wd1.success=true;
		      wd1.txt = buffer.toString();
		      wd1.count = buffer.toString().length();
	      return wd;*/
	 }
	 
	 /**
	  * 提取docx文件
	  */
	 
	 public WordDTO getXWordTxt( String fp) throws Exception{
		 InputStream is = new FileInputStream(fileService.getPathUpload()+fp);  
		 XWPFDocument docx = new XWPFDocument(is);
		 XWPFWordExtractor xwpfWordExtractor = new XWPFWordExtractor(docx);
		 //int count1 = docx.getProperties().getExtendedProperties().getUnderlyingProperties().getWords();
		 int count = docx.getProperties().getExtendedProperties().
				 getUnderlyingProperties().getCharacters();
		 WordDTO wd = new WordDTO(true, xwpfWordExtractor.getText(), 
				count );
		 xwpfWordExtractor.close();
		 return wd;
	 }
}
